package com.zzvcom.office.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzvcom.office.documentserver.storage.FileStorageMutator;
import com.zzvcom.office.entities.OfficeFile;
import com.zzvcom.office.entities.User;
import com.zzvcom.office.sdk.manager.DocumentManager;
import com.zzvcom.office.services.UserServices;
import com.zzvcom.office.vo.UploadFileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yujikuan
 * @description
 */
@Component
public class UserMetadataUtil {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserServices userService;
    @Autowired
    private DocumentManager documentManager;
    @Autowired
    private FileStorageMutator storageMutator;

    /**
     * 文件的原信息可以放入数据库中，暂时存放在文件名中
     * @param uid 用户账号
     * @param officeFile 文件实体
     * @return
     */
    public String createUserMetadata(final String uid, OfficeFile officeFile) {
        User optionalUser = userService.findUserById(Integer.parseInt(uid));  // find a user by their ID
        // get document type
        String documentType = documentManager.getDocumentType(officeFile.getName()).
                toString().toLowerCase();
        if (optionalUser!=null) {

            //// create meta information with the user ID and name specified
            storageMutator.createMeta(officeFile, officeFile.getName(),
                    String.valueOf(optionalUser.getId()), optionalUser.getName());
        }
        UploadFileVO uploadFileVO = new UploadFileVO(officeFile);
        uploadFileVO.setDocumentType(documentType);
        try {
            return objectMapper.writeValueAsString(uploadFileVO);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
